package com.yunyao.framework.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yunyao.client.request.PageRequest;
import com.yunyao.client.request.ProjectRequest;
import com.yunyao.client.request.UserRequest;
import com.yunyao.client.response.ProjectResponse;
import com.yunyao.client.response.UserResponse;
import com.yunyao.client.service.MdmClientService;
import com.yunyao.common.constant.enums.DataDeletedStatus;
import com.yunyao.common.core.BaseContext;
import com.yunyao.common.dto.UserDto;
import com.yunyao.common.dto.project.ProjectDto;
import com.yunyao.common.sign.Md5Util;
import com.yunyao.common.web.enums.ResultMsgEnum;
import com.yunyao.common.web.util.ConvertUtil;
import com.yunyao.common.web.util.PageResult;
import com.yunyao.common.web.util.YResult;
import com.yunyao.dao.mapper.BamuSysDeptMapper;
import com.yunyao.dao.model.BamuProject;
import com.yunyao.dao.model.BamuSaleContract;
import com.yunyao.dao.model.BamuSysDept;
import com.yunyao.dao.model.User;
import com.yunyao.dao.service.bamu.IBamuProjectService;
import com.yunyao.dao.service.bamu.IBamuSaleContractService;
import com.yunyao.framework.dto.project.ProjectSaveDto;
import com.yunyao.framework.service.ProjectService;
import com.yunyao.framework.vo.project.ProjectInfoVO;
import com.yunyao.framework.vo.project.ProjectVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author xingjishuai
 * @date 2024-07-16
 */
@Slf4j
@Service
public class ProjectServiceImpl implements ProjectService {
    @Autowired
    private MdmClientService mdmClientService;
    @Autowired
    private IBamuProjectService iBamuProjectService;

    @Autowired
    private IBamuSaleContractService iBamuSaleContractService;

    @Autowired
    private BamuSysDeptMapper bamuSysDeptMapper;

    @Override
    public YResult<PageResult<ProjectVO>> pageList(ProjectDto projectDto) {
        // 构建查询条件
        Long pageIndex = projectDto.getPageIndex();
        Long pageSize = projectDto.getPageSize();
        String projectName = projectDto.getProjectName();
        String projectType = projectDto.getProjectType();
        String deptId = projectDto.getDeptId();
        String ancestors = getAncestorsByDeptId(deptId);
        List<String> projectList = BaseContext.getProjectList();
        // 分页查询
        IPage<BamuProject> payPage = iBamuProjectService.pageList(projectName, projectType,
                projectList, ancestors,
                pageIndex, pageSize);

        // 处理查询结果
        if (CollectionUtils.isEmpty(payPage.getRecords())) {
            return YResult.success(new PageResult<>());
        }

        // 转换为VO对象列表
        List<ProjectVO> projectVOList = projectDaoToVoList(payPage.getRecords());

        // 返回分页结果
        return YResult.success(new PageResult<>(projectVOList, payPage.getCurrent(), payPage.getSize(), payPage.getPages(), payPage.getTotal()));
    }

    @Override
    public YResult<ProjectInfoVO> getProjectById(String id) {
        BamuProject bamuProject = iBamuProjectService.getByIdNoDel(id);
        // 处理查询结果
        if (Objects.isNull(bamuProject)) {
            return YResult.success();
        }
        return YResult.success(daoToInfoVO(bamuProject));
    }

    @Override
    public YResult<Boolean> deleteInfo(String id) {
        // 根据ID查询要删除的BamuPoSupply对象
        BamuProject bamuProject = iBamuProjectService.getById(id);

        List<BamuSaleContract> bamuSaleContractList = iBamuSaleContractService.lambdaQuery().eq(BamuSaleContract::getProjectId, id).eq(BamuSaleContract::getIsDeleted, DataDeletedStatus.NO.getType()).list();

        if (CollectionUtils.isNotEmpty(bamuSaleContractList)) {
            return YResult.error("该项目下存在未删除的合同，请先删除该项目的所有合同");
        }

        // 如果对象不存在，返回错误信息
        if (bamuProject == null) {
            return YResult.error(ResultMsgEnum.NO_DATA);
        }
        return YResult.success(iBamuProjectService.deleteById(id));
    }

    @Override
    public YResult<String> saveInfo(ProjectSaveDto saveDto) {
        try {
            if (StringUtils.isNotBlank(saveDto.getId())) {
                // 修改
                BamuProject bamuProject = iBamuProjectService.getByIdNoDel(saveDto.getId());
                if (bamuProject == null) {
                    return YResult.error(ResultMsgEnum.NO_DATA);
                }
            }
            BamuProject bamuProject = new BamuProject();
            BeanUtils.copyProperties(saveDto,bamuProject);
            bamuProject.setExpireTime(ConvertUtil.getString2Date(saveDto.getExpireTime()));
            iBamuProjectService.saveOrUpdate(bamuProject);
            return YResult.success("操作成功");
        } catch (Exception ex) {
            log.error("保存项目信息异常", ex);
            return YResult.error(ex.getMessage());
        }

    }

    private ProjectInfoVO daoToInfoVO(BamuProject bamuProject) {
        ProjectInfoVO projectInfo =  new ProjectInfoVO();
        BeanUtils.copyProperties(bamuProject, projectInfo);
        return projectInfo;
    }
    private List<ProjectVO> projectDaoToVoList(List<BamuProject> records) {
        return records.stream().map(this::projectDaoToVo).collect(Collectors.toList());
    }

    private ProjectVO projectDaoToVo(BamuProject bamuProject) {
        ProjectVO projectVO = new ProjectVO();
        BeanUtils.copyProperties(bamuProject, projectVO);
        return projectVO;
    }

    private String getAncestorsByDeptId(String deptId) {
        if (StringUtils.isBlank(deptId)) {
            return null;
        }
        BamuSysDept bamuSysDept = bamuSysDeptMapper.selectById(deptId);
        if (bamuSysDept == null) {
            return null;
        }
        return bamuSysDept.getAncestors() + deptId;
    }

    @Override
    public YResult<String> syncMdm(ProjectDto projectDto) {
        try {
            syncMdmHandle(projectDto);
            return YResult.success("同步成功");
        } catch (Exception ex) {
            log.error("同步用户信息失败", ex);
            return YResult.error(ex.getMessage());
        }
    }

    @Async
    public void syncMdmHandle(ProjectDto projectDto) {
        String beginDate = projectDto.getBeginDate();
        ProjectRequest userRequest = new ProjectRequest();
        userRequest.setLastModifyRecordTime(beginDate + "~");
        long pageIndex = 1;
        List<ProjectResponse> records = new ArrayList<>();
        do {
            PageRequest pageRequest = new PageRequest();
            pageRequest.setPageIndex(pageIndex);
            pageRequest.setPageSize(50L);
            PageResult<ProjectResponse> responsePageResult =
                    mdmClientService.projectPageList(userRequest, pageRequest);
            records = responsePageResult.getRecords();
            if (CollectionUtils.isEmpty(records) || pageIndex > responsePageResult.getTotalPages()) {
                break;
            }
            for (ProjectResponse userResponse : records) {
                String projectCode = userResponse.getProjectCode();
                String projectName = userResponse.getProjectName();
                if (StringUtils.isBlank(projectCode) && StringUtils.isBlank(projectName)) {
                    continue;
                }
                BamuProject project = iBamuProjectService.getByCode(projectCode, projectName);
                if (Objects.nonNull(project)){
                    continue;
                }
                BamuProject project2 = new BamuProject();
                project2.setProjectCode(userResponse.getProjectCode());
                project2.setProjectName(userResponse.getProjectName());
                project2.setProjectSortname(userResponse.getProjectSortname()); // 假设DTO中也有相应的getter
                project2.setProjectAddress(userResponse.getProjectAddress());
                project2.setOrgId(userResponse.getOrgId());
                project2.setOrgName(userResponse.getOrgName());
                project2.setPurchaseDeptName(userResponse.getPurchaseDeptName()); // 假设DTO中也有DESC4的getter
                project2.setDeptId(userResponse.getDeptId());
                project2.setDeptName(userResponse.getDeptName());
                project2.setProvinceId(userResponse.getProvinceId());
                project2.setProvinceName(userResponse.getProvinceName());
                project2.setCityId(userResponse.getCityId());
                project2.setCityName(userResponse.getCityName());
                project2.setDistrictId(userResponse.getDistrictId());
                project2.setDistrictName(userResponse.getDistrictName());
                iBamuProjectService.save(project2);
            }
            pageIndex++;
        } while (CollectionUtils.isNotEmpty(records));
    }


}
